<!--竞赛信息页面-->
<template>
    <div>
        <div style="display: flex;align-items: center;justify-content: center">
            <el-input style="width: 150px" placeholder="查询名称" v-model="title" clearable></el-input>
            <el-select style="width: 100px; margin: 0 10px" v-model="sign" placeholder="竞赛类型">
                <el-option v-for="item in options" :key="item" :label="item" :value="item"></el-option>
            </el-select>
            <el-button type="primary" style="margin-left: 10px" @click="load(1)">查询</el-button>
            <el-button type="info" @click="reset" plain>重置</el-button>
        </div>
        <div style="margin: 10px 0">
            <el-button type="primary" plain @click="handleAdd" v-if="user.role === '管理员' || user.role === '教师'"
            >新增</el-button>
            <el-button type="danger"  plain @click="delBatch" v-if="user.role === '管理员'">批量删除</el-button>
        </div>
        <el-table :data="tableData"
                  stripe
                  :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666'}"
                  style="font-size: 14px"
                  @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column prop="title" label="竞赛名称" align="center"></el-table-column>
            <el-table-column prop="description" label="简介" align="center"></el-table-column>
            <el-table-column prop="sign" label="竞赛类型" align="center"></el-table-column>
            <el-table-column v-slot="scope" prop="pay" label="付费模式" align="center">
                <el-tag v-if="scope.row.pay === '免费'" style="font-size: 14px" type="success">免费</el-tag>
                <el-tag v-if="scope.row.pay === '付费'" style="font-size: 14px" type="warning">付费</el-tag>
            </el-table-column>
            <el-table-column prop="money" label="付费金额" align="center"></el-table-column>
            <el-table-column v-slot="scope" prop="contintime" label="报名时间" show-overflow-tooltip align="center">
                {{scope.row.startime}} - {{scope.row.endtime}}
            </el-table-column>
            <el-table-column prop="author" label="发布人" align="center"></el-table-column>
            <el-table-column prop="num" label="已报名" align="center"></el-table-column>
            <el-table-column label="操作" align="center" width="220">
                <template v-slot="scope" style="font-size: 14px" >
                    <el-button style="padding: 6px" type="success" plain @click="$router.push('/newsDetail?id=' + scope.row.id)" size="mini">详情</el-button>
                    <el-button style="padding: 6px" type="warning" v-if="user.role === '学生'" plain @click="$router.push('/enrollForm?id=' + scope.row.id)" size="mini">报名</el-button>
                    <el-button style="padding: 6px" size="mini" type="primary" plain @click="handleEdit(scope.row)" v-if="user.role === '管理员'
                    || user.role === '教师'">编辑</el-button>
                    <el-button style="padding: 6px" size="mini" type="danger" plain @click="del(scope.row.id)" v-if="user.role === '管理员'"
                    >删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin: 10px 0; display: flex; align-items: center; justify-content: center">
            <el-pagination
                    @current-change="handleCurrentChange"
                    :current-page="pageNum"
                    :page-size="pageSize"
                    layout="total, prev, pager, next"
                    :total="total">
            </el-pagination>
        </div>

<!--        弹窗-->
        <el-dialog title="竞赛信息" :visible.sync="fromVisible" width="60%" @close="closeDialog" :close-on-click-modal="false">
            <el-form :model="form" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
                <el-form-item label="竞赛标题" prop="title">
                    <el-input v-model="form.title" placeholder="竞赛标题"></el-input>
                </el-form-item>
                <el-form-item label="竞赛类型" prop="sign" >
                    <el-select v-model="form.sign" placeholder="请选择竞赛类型">
                        <el-option
                                v-for="item in options" :key="item"
                                :label="item"
                                :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="付费模式" prop="pay">
                    <el-select v-model="form.pay" placeholder="请选择付费模式">
                        <el-option
                                v-for="item in pays"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="form.pay === '付费'" label="付费金额">
                    <el-input-number
                            v-model="form.money"
                            :min="0"
                            :max="9999"
                            controls-position="right"
                            :step="10"
                    >
                    </el-input-number>
                </el-form-item>
                <el-form-item label="简介" prop="description">
                    <el-input v-model="form.description" placeholder="简介"></el-input>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <div id="editor"></div>
                </el-form-item>
                <el-form-item label="报名时间" prop="contintime">
                    <div class="block">
                        <el-date-picker
                                v-model="form.contintime"
                                type="datetimerange"
                                format="yyyy-MM-dd HH:mm:ss"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                        </el-date-picker>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="fromVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>

    </div>

</template>

<script>
    import E from "wangeditor"
    import hljs from "highlight.js"
    export default {
        name: "News",
        data() {
            return {
                tableData:[], //所有的数据
                pageNum: 1, //当前的页码
                pageSize: 6, //每页显示的个数
                title: '',
                sign:'',
                //竞赛类型
                options: [],
                //是否付费
                pays: [{
                    value: '免费',
                    label: '免费',
                }, {
                    value: '付费',
                    label: '付费',
                }],
                total: 0, //默认是0
                fromVisible: false,
                form: {
                    contintime: '',
                },
                user: JSON.parse(localStorage.getItem("honey-user") || '{}'),//拿取个人用户信息
                rules: {
                    title: [
                        {required: true, message: '请输入竞赛标题', trigger: 'blur'}
                    ],
                    sign: [
                        {required: true, message: '请选择竞赛类型', trigger: 'blur'}
                    ],
                    pay: [
                        {required: true, message: '请选择付费模式', trigger: 'blur'}
                    ],
                    description: [
                        {required: true, message: '请输入简介', trigger: 'blur'}
                    ],
                    contintime: [
                        {required: true, message: '请选择竞赛时间', trigger: 'blur'}
                    ],
                },
                ids: [],
                editor: null,
                content: '',
                fromVisible1: false,
            }
        },
        created() {
            this.load()
        },
        methods: {
            showContent(content){
                this.content = content
                this.fromVisible1 = true
            },
            closeDialog(){
              //销毁编辑器
              this.editor.destroy()
              this.editor = null
            },
            delBatch(){ //批量删除
                if (!this.ids.length){
                    this.$message.warning('请选择数据')
                    return
                }
                this.$confirm('确认批量删除这些数据吗？','确认删除',{type: "warning"}).then(response => {
                    this.$request.delete('/news/delete/batch', {
                        data: this.ids
                    }).then(res => {
                        if (res.code === '200'){ //操作成功
                            this.$message.success('操作成功')
                            this.load(1) //刷新表格数据
                        }else { //操作失败
                            this.$message.error(res.msg) //弹出错误信息
                        }
                    })
                }).catch(() => {})
            },
            handleSelectionChange(rows){ //选中的数据 rows:当前选中的所有行数据
                this.ids = rows.map(v => v.id)
            },
            del(id){ //单个删除
                this.$confirm('确认删除？','确认删除',{type: "warning"}).then(response => {
                    this.$request.delete('/news/delete/' + id).then(res => {
                        if (res.code === '200'){ //操作成功
                            this.$message.success('操作成功')
                            this.load(1) //刷新表格数据
                        }else { //操作失败
                            this.$message.error(res.msg) //弹出错误信息
                        }
                    })
                }).catch(() => {})
            },
            setRichText(){ //富文本设置
                this.$nextTick(() => {
                    this.editor = new E('#editor') // #绑定id 初始化富文本的区域
                    this.editor.highlight = hljs
                    //图片上传
                    this.editor.config.uploadImgServer = this.$baseUrl + '/file/editor/upload'
                    this.editor.config.uploadFileName = 'file'
                    this.editor.config.uploadImgHeaders = {
                        token: this.user.token
                    }
                    this.editor.config.uploadImgParams = {
                        type: 'img'
                    }
                    //视频上传
                    this.editor.config.uploadVideoServer = this.$baseUrl + '/file/editor/upload'
                    this.editor.config.uploadVideoName = 'file'
                    this.editor.config.uploadVideoHeaders = {
                        token: this.user.token
                    }
                    this.editor.config.uploadVideoParams = {
                        type: 'video'
                    }
                    this.editor.create() //创建
                }) //$nextTick等div元素划分好区域后再创建富文本区域
            },
            handleEdit(row){ //编辑
                this.form = JSON.parse(JSON.stringify(row)) //给form对象赋值 注意要深拷贝数据
                this.fromVisible = true //打开弹窗
                this.setRichText()
                setTimeout( () => { //延迟设置
                    this.editor.txt.html(row.content) //设置富文本内容
                }, 0)
            },
            handleAdd(){
                this.form = {} //新增数据的时候清空数据
                this.fromVisible = true //打开新增弹窗
                this.setRichText()
            },
            save(){ //保存
                this.$refs.formRef.validate((valid) => {
                    if(valid){ //验证通过
                        //获取编辑框的信息
                        let content = this.editor.txt.html()
                        let Datetime=this.form.contintime.toString();
                        console.log(Datetime)
                        this.form.content = content //设置form表单
                        this.form.contintime =Datetime
                        this.$request({
                            url: this.form.id ? '/news/update' : '/news/add',
                            method: this.form.id ? 'PUT' : 'POST', //判断有无id,有为编辑,无为新增
                            data: this.form
                        }).then(res => {
                            if (res.code === '200'){ //成功保存
                                this.$message.success('保存成功')
                                this.load(1)
                                this.fromVisible = false
                            }else { //保存失败
                                this.$message.error(res.msg) //弹出错误信息
                            }
                        })

                    }
                })
            },
            reset(){
                this.title = ''
                this.sign = ''
                this.load()
            },
            load(pageNum){ //分页查询
                if (pageNum){
                    this.pageNum = pageNum
                }
                this.$request.get('/news/selectByPage', {
                    params: {
                        pageNum: this.pageNum,
                        pageSize: this.pageSize,
                        title: this.title,
                        sign: this.sign,
                        pay: this.pay
                    }
                }).then(res => {
                    this.tableData = res.data.records
                    console.log(this.tableData)
                    this.total = res.data.total
                })
                //接收竞赛类型值
                this.$request.get('/sign/selectAll').then(res => {
                    this.options = res.data
                })
            },
            handleCurrentChange(pageNum){
                this.load(pageNum)
            },
        }
    }

</script>

<style scoped>

</style>